import { createWebHistory, createRouter } from 'vue-router'
import i18n from '@/locales'
import { getToken } from '@/utils/token'

import HomeView from '@/views/HomeView.vue'
import Login from '@/views/Login/User.vue'
import Account from '@/views/Account/Index.vue'

const routes = [
  { path: '/', name: 'home', meta: { title: 'home' }, component: HomeView },
  {
    path: '/login',
    name: 'login',
    meta: { title: 'userLogin' },
    component: Login
  },
  {
    path: '/account',
    name: 'account',
    meta: { title: 'account', private: true },
    component: Account
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  document.title = i18n.global.t(to.meta.title) + ' - Xing-api vue3'

  const token = getToken()
  if (to.meta.private) {
    if (token) {
      next()
    } else {
      next('/login?redirect=' + to.name)
    }
  } else {
    if (token) {
      if (to.name == 'login' || to.name == 'register') {
        next('/account')
      }
    } else {
      next()
    }
  }
})

export default router
